<template>
  <div class="custom-image">
    <img v-if="isLoadSvg" v-img-error class="custom-image-svg" :src="imgSrc" />
    <!-- preset="default" 这个被 class 覆盖了 -->
    <nuxt-picture
      v-else
      v-img-error
      :format="IMAGE_FORMATS.join(',')"
      :class="['custom-image-cover']"
      :src="imgSrc"
      :alt="alt"
      :placeholder="placeholder"
      quality="100"
      preload
      densities="x1 x2"
      loading="lazy"
      @onerror="handleError"
    />
  </div>
</template>

<script setup lang="ts">
import { IMAGE_FORMATS } from "~~/config";
import { getOssFileUrl, getImagePrefix } from "@/utils";

const props = withDefaults(
  defineProps<{
    src?: string;
    alt?: string;
    placeholder?: string;
    isHttp?: boolean; // 是不是网络图片：默认不是
    fit?: string;
  }>(),
  {
    src: "",
    fit: "cover",
  }
);
// const { WEB_NODE_ENV = "prod" } = useRuntimeConfig().public;

const imgErrorFit = ref("");
const imgFit = computed(() => {
  return imgErrorFit.value || props.fit;
});
const imgUrl = getOssFileUrl({
  placeholder: "/image/placeholder.png",
});

const src_error = ref("");
// 拼接正确的 src
const imgSrc = computed({
  get() {
    // console.log(props.isHttp, "--props.src--", props.src);
    if (src_error.value) return src_error.value;
    let u = props.src;
    if (!u) u = props.placeholder || imgUrl.placeholder; // 如果没有图片链接,就加载默认:占位图
    if (!props.isHttp) return u; // 是否需要增加前缀
    if (u.startsWith("http")) return u; // 如果存在http前缀,直接加载
    return getImagePrefix(u); // 增加 http 环境前缀,并加载
  },
  set(value) {
    src_error.value = value;
    imgErrorFit.value = "contain";
  },
});

// 加载 svg 用 img 标签，nuxt-picture加载很模糊
const isLoadSvg = ref(false);
watch(
  () => props.src,
  (newVal) => {
    if (newVal && newVal.endsWith(".svg")) {
      imgSrc.value = `${process.env.NODE_ENV == "development" ? "" : "/fx"}${
        imgSrc.value
      }`;
      isLoadSvg.value = true;
    } else {
      isLoadSvg.value = false;
    }
  },
  {
    immediate: true,
  }
);

// 加载失败，赋值默认图片
const handleError = () => {
  // console.error("imgSrc.value 错误", imgSrc.value);
  imgSrc.value = props.placeholder || imgUrl.placeholder;
};
</script>

<style scoped lang="scss">
.custom-image {
  &-svg {
    display: block !important;
    object-fit: v-bind("imgFit");
    width: 100%;
    height: 100%;
  }
  &-cover {
    display: flex;
    justify-content: center;
    align-items: center;
    width: inherit;
    height: inherit;
    user-select: none;

    :deep(img) {
      object-fit: v-bind("imgFit");
      width: 100%;
      height: 100%;
    }
  }
}
</style>
